<html>
<head>
<title>C++ Annotations Version 6.5.0</title>
</head>
<body text="black" bgcolor="white">
<hr>
<ul>
    <li> <a href="cplusplus.html">Table of Contents</a>
    <li> <a href="cplusplus14.html">Previous Chapter</a>
    <li> <a href="cplusplus16.html">Next Chapter</a>
</ul>
<hr>
<a name="PointMembers"></a><a name="l215"></a>
<h1>Chapter 15: Classes having pointers to members</h1>
<a name="pointermembers"></a>
<blockquote>
    <em>
        Don't hesitate to send in feedback: send an e-mail if you like the
        C++ Annotations; if you think that important material was omitted;
        if you find errors or typos in the text or the code examples;
        or if you just feel like e-mailing. Send your e-mail to
        <a href="mailto:f.b.brokken@rug.nl">Frank B. Brokken</a>.
<p>
<strong>Please</strong> state the document version you're referring to, as found in
        the title (in this document: 6.5.0) and please state chapter and
        paragraph name or number you're referring to.
<p>
All received mail is processed conscientiously, and received
        suggestions for improvements will usually have been processed by the
        time a new version of the Annotations is released. Except for the
        incidental case I will normally not acknowledge the receipt of
        suggestions for improvements. Please don't interpret this as me not
        appreciating your efforts.
    </em>
</blockquote>
<p>
<a name="pointermembers/intro"></a>Classes having <code>pointer data members</code> have been discussed in detail in
chapter <a href="cplusplus07.html#MEMORY">7</a>.  As we have seen, when pointer data-members occur in
classes, such classes deserve some special treatment.
<p>
By now it is well known how to treat pointer data members: constructors are
used to initialize pointers, destructors are needed to delete the memory
pointed to by the pointer data members.
<p>
Furthermore, in classes having pointer data members copy constructors and
overloaded assignment operators are normally needed as well.
<p>
However, in some situations we do not need a pointer to an object, but rather
a <a name="an2100"></a>
pointer to members of an object. In this chapter these special pointers
are the topic of discussion.
<p>
<a name="l216"></a>
<h2>15.1: Pointers to members: an example</h2>
    <a name="pointermembers/example"></a>Knowing how pointers to variables and objects are used does not intuitively
lead to the concept of <em>pointers to members</em> <a name="an2101"></a>
. Even if
the return types and parameter types of member functions are taken into
account, surprises are likely to be encountered.  For example, consider the
following class:
        <pre>
    class String
    {
        char const *(*d_sp)() const;

        public:
            char const *get() const;
    };
</pre>
    For this class, it is not possible to let a <code>char const *(*d_sp)()
const</code> data member point to the <code>get()</code> member function of the <code>String</code>
class: <code>d_sp</code> cannot be given the address of the member function <code>get()</code>.
<p>
One of the reasons why this doesn't work is that the variable <code>d_sp</code> has
<a name="an2102"></a>
global scope, while the member function <code>get()</code> is defined within the
<code>String</code> class, and has <code>class scope</code>. The fact that the variable <code>d_sp</code>
is part of the <code>String</code> class is irrelevant. According to <code>d_sp</code>'s
definition, it points to a function living <em>outside</em> of the class.
<p>
Consequently, in order to define a pointer to a member (either data or
function, but usually a function) of a class, the scope of the pointer must be
within the class's scope.  Doing so, a pointer to a member of the class
<code>String</code> can be defined as
        <pre>
    char const *(String::*d_sp)() const;
</pre>
    So, due to the <code>String::</code> prefix, <code>d_sp</code> is defined as a pointer only
in the context of the class <code>String</code>. It is defined as a pointer to a
function in the class <code>String</code>, not expecting arguments, not modifying its
object's data, and returning a pointer to constant characters.
<p>
<a name="l217"></a>
<h2>15.2: Defining  pointers to members</h2>
    <a name="pointermembers/defining"></a>Pointers <a name="an2103"></a>
 to members are defined by prefixing
the normal <a name="an2104"></a>
pointer notation with the appropriate class plus
    <a name="an2105"></a>
scope resolution operator. Therefore, in the previous section, we used
<code>char const * (String::*d_sp)() const</code> to indicate:
    <ul>
    <li><code>d_sp</code> is a pointer (<code>*d_sp</code>),
    <li> to something in the class <code>String</code> (<code>String::*d_sp</code>).
    <li> It is a pointer to a <code>const</code> function, returning a <code>char const *</code>:
            <code>char const * (String::*d_sp)() const</code>
    <li> The prototype of the corresponding function is therefore:
        <pre>
        char const *String::somefun() const;
</pre>
    a <code>const</code> parameterless function in the class <code>String</code>, returning a
<code>char const *</code>.
    </ul>
    Actually, the normal procedure for <a name="an2106"></a>
constructing pointers can still be
applied:
    <ul>
    <li> put parentheses around the function name (and its class name):
        <pre>
        char const * ( String::somefun ) () const
</pre>
    <li> Put a pointer (a star (<code>*</code>)) character immediately before the
function-name itself:
        <pre>
        char const * ( String:: * somefun ) () const
</pre>
    <li> Replace the function name with the name of the pointer variable:
        <pre>
        char const * (String::*d_sp)() const
</pre>
    </ul>
    Another example, this time defining a pointer to a data member. Assume the
class <code>String</code> contains a <code>string d_text</code> member. How to construct a
pointer to this member? Again we follow the basic procedure:
    <ul>
    <li> put parentheses around the variable name (and its class name):
        <pre>
        string (String::d_text)
</pre>
    <li> Put a pointer (a star (<code>*</code>)) character immediately before the
variable-name itself:
        <pre>
        string (String::*d_text)
</pre>
    <li> Replace the variable name with the name of the pointer variable:
        <pre>
        string (String::*tp)
</pre>
    In this case, the parentheses are superfluous and may be omitted:
        <pre>
        string String::*tp
</pre>
    </ul>
    Alternatively, a very simple <a name="an2107"></a>
rule of thumb is
    <ul>
    <li> Define a normal (i.e., global) pointer variable,
    <li> Prefix the class name to the pointer character, once you point to
something inside a class
    </ul>
    For example, the following pointer to a global function
        <pre>
    char const * (*sp)() const;
</pre>
    becomes a pointer to a member function after prefixing the class-scope:
        <pre>
    char const * (String::*sp)() const;
</pre>
    Nothing in the above discussion forces us to define these pointers to
members in the <code>String</code> class itself. The pointer to a member may be defined
in the class (so it becomes a data member itself), or in another class, or as
a local or global variable. In all these cases the pointer to member
variable can be given the address of the kind of member it points to. The
important part is that a pointer to member can be initialized or assigned
without the need for an object of the corresponding class.
<p>
Initializing or assigning an address to such a pointer does nothing but
indicating to which member the pointer will point. This  can be
considered a kind of <a name="an2108"></a>
<em>relative address</em>: relative to the object for which
the function is called. No object is required when pointers to members are
initialized or assigned. On the other hand, while it is allowed to initialize
or assign a pointer to member, it is (of course) not possible to <em>access</em>
these members without an associated object.
<p>
In the following example <a name="an2109"></a>

    <a name="an2110"></a>
 initialization of and assignment to
pointers to members is illustrated (for illustration purposes all members of
<code>PointerDemo</code> are defined <code>public</code>). In the example itself, note the use
of the <code>&amp;</code>-operator to determine the addresses of the members. These
operators, as well as the class-scopes are required. Even when used inside the
class member implementations themselves:
        <pre>
    class PointerDemo
    {
        public:
            unsigned d_value;
            unsigned get() const;
    };

        inline unsigned PointerDemo::get() const
        {
            return d_value;
        }

    int main()
    {                                           // initialization
        unsigned (PointerDemo::*getPtr)() const = &amp;PointerDemo::get;
        unsigned PointerDemo::*valuePtr         = &amp;PointerDemo::d_value;

        getPtr   = &amp;PointerDemo::get;           // assignment
        valuePtr = &amp;PointerDemo::d_value;
    }
</pre>
    Actually, nothing special is involved: the difference with pointers at
<a name="an2111"></a>
global scope is that we're now restricting ourselves to the scope of the
<code>PointerDemo</code> class. Because of this restriction, all <em>pointer</em>
definitions and all variables whose addresses are used must be given the
<code>PointerDemo</code> class scope. Pointers to members can also be used with
<code>virtual</code>
        <a name="an2112"></a>

    member functions. No further changes are required if, e.g., <code>get()</code> is
defined as a virtual member function.
<p>
<a name="l218"></a>
<h2>15.3: Using pointers to members</h2>
    <a name="pointermembers/using"></a>In the previous section we've seen how to define pointers to member
functions. In order to use these pointers, an object is <em>always</em> required.
With pointers operating at global scope, the <a name="an2113"></a>
dereferencing operator <code>*</code>
is used to reach the object or value the pointer points to.
With pointers to objects the <a name="an2114"></a>
field selector operator operating on pointers
(<a name="an2115"></a>
<code>-&gt;</code>) or the field selector operating operating on objects (<code>.</code>) can be
used to select appropriate members.
<p>
To use a pointer to member in combination with an object the
    <a name="an2116"></a>
pointer to member field selector (<a name="an2117"></a>
<code>.*</code>) must be used.  To use a
pointer to a member via a pointer to an object the `pointer to member field
selector through a pointer to an object' (<a name="an2118"></a>
<code>-&gt;*</code>) must be used. These two
operators combine the notions of, on the one hand, a field selection (the
<code>.</code> and <code>-&gt;</code> parts) to reach the appropriate field in an object and, on
the other hand, the notion of dereferencing: a <a name="an2119"></a>
dereference operation is
used to reach the function or variable the pointer to member points to.
<p>
Using the example from the previous section, let's see how we can use the
pointer to member function and the pointer to data member:
            <pre>
    #include &lt;iostream&gt;

    class PointerDemo
    {
        public:
            unsigned d_value;
            unsigned get() const;
    };

        inline unsigned PointerDemo::get() const
        {
            return d_value;
        }

    using namespace std;

    int main()
    {                                           // initialization
        unsigned (PointerDemo::*getPtr)() const = &amp;PointerDemo::get;
        unsigned PointerDemo::*valuePtr   = &amp;PointerDemo::d_value;

        PointerDemo object;                     // (1) (see text)
        PointerDemo *ptr = &amp;object;

        object.*valuePtr = 12345;               // (2)
        cout &lt;&lt; object.*valuePtr &lt;&lt; endl;
        cout &lt;&lt; object.d_value &lt;&lt; endl;

        ptr-&gt;*valuePtr = 54321;                 // (3)
        cout &lt;&lt; object.d_value &lt;&lt; endl;

        cout &lt;&lt; (object.*getPtr)() &lt;&lt; endl;     // (4)
        cout &lt;&lt; (ptr-&gt;*getPtr)() &lt;&lt; endl;
    }
</pre>
    We note:
    <ul>
    <li> At statement (1) a <code>PointerDemo</code> object and a pointer to such an
object is defined.
    <li> At statement (2) we specify an object, and hence the <code>.*</code> operator,
to reach the member <code>valuePtr</code> points to. This member is given a value.
    <li> At statement (3) the same member is assigned another value, but this
time using the pointer to a <code>PointerDemo</code> object. Hence we use the
<code>-&gt;*</code> operator.
    <li> At statement (4) the <code>.*</code> and <code>-&gt;*</code> are used once again, but this
time to call a function through a pointer to member. Realize that the function
argument list has a higher priority than pointer to member field selector
    <a name="an2120"></a>

operator, so the latter <em>must</em> be protected by its own set of parentheses.
    </ul>
    Pointers to members can be used profitably in situations where a class has
a member which behaves differently depending on, e.g., a configuration
state. Consider once again a class <code>Person</code> from section
<a href="cplusplus07.html#DESTRUCTOR">7.2</a>. This class contains fields holding a person's name, address
and phone number. Let's assume we want to construct a <code>Person</code> data base of
employees.  The employee data base can be queried, but depending on the kind of
person querying the data base either the name, the name and phone number or
all stored information about the person is made available. This implies that a
member function like <code>address()</code> must return something like `<code>&lt;not
available&gt;</code>' in cases where the person querying the data base is not allowed
to see the person's address, and the actual address in other cases.
<p>
Assume the employee data base is opened with an argument reflecting the
status of the employee who wants to make some queries. The status could
reflect his or her position in the organization, like <code>BOARD</code>,
<code>SUPERVISOR</code>, <code>SALESPERSON</code>, or <code>CLERK</code>. The first two categories are
allowed to see all information about the employees, a <code>SALESPERSON</code> is
allowed to see the employee's phone numbers, while the <code>CLERK</code> is only
allowed to verify whether a person is actually a member of the organization.
<p>
We now construct a member <code>string personInfo(char const *name)</code> in the
data base class. A standard implementation of this class could be:
        <pre>
    string PersonData::personInfo(char const *name)
    {
        Person *p = lookup(name);   // see if `name' exists

        if (!p)
            return "not found";

        switch (d_category)
        {
            case BOARD:
            case SUPERVISOR:
                return allInfo(p);
            case SALESPERSON:
                return noPhone(p);
            case CLERK:
                return nameOnly(p);
        }
    }
</pre>
    Although it doesn't take much time, the <code>switch</code> must nonetheless be
evaluated every time <code>personCode()</code> is called. Instead of using a switch, we
could define a member <code>d_infoPtr</code> as a pointer to a member function of the
class <code>PersonData</code> returning a <code>string</code> and expecting a <code>Person</code>
reference as its argument. Note that this pointer can now be used to point to
<code>allInfo()</code>, <code>noPhone()</code> or <code>nameOnly()</code>. Furthermore, the function that
the pointer variable points to will be known by the time the <code>PersonData</code>
object is constructed, assuming that the employee status is given as an
argument to the constructor of the <code>PersonData</code> object.
<p>
After having set the <code>d_infoPtr</code> member to the appropriate member
function, the <code>personInfo()</code> member function may now be rewritten:
        <pre>
    string PersonData::personInfo(char const *name)
    {
        Person *p = lookup(name);       // see if `name' exists

        return p ? (this-&gt;*d_infoPtr)(p) :  "not found";
    }
</pre>
    Note the syntactical construction when using a pointer to member from
        <a name="an2121"></a>

within a class: <code>this-&gt;*d_infoPtr</code>.
<p>
The member <code>d_infoPtr</code> is defined as follows (within the class
<code>PersonData</code>, omitting other members):
        <pre>
    class PersonData
    {
        string (PersonData::*d_infoPtr)(Person *p);
    };
</pre>
    Finally, the constructor must initialize <code>d_infoPtr</code> to point to the
correct member function. The constructor could, for example, be given the
following code (showing only the pertinent code):
        <pre>
    PersonData::PersonData(PersonData::EmployeeCategory cat)
    {
        switch (cat)
        {
            case BOARD:
            case SUPERVISOR:
                d_infoPtr = &amp;PersonData::allInfo;
            case SALESPERSON:
                d_infoPtr = &amp;PersonData::noPhone;
            case CLERK:
                d_infoPtr = &amp;PersonData::nameOnly;
        }
    }
</pre>
    Note how addresses of member functions are determined: the class
<code>PersonData</code> scope <em>must</em> be specified, even though we're already inside
a member function of the class <code>PersonData</code>.
<p>
An example using <a name="an2122"></a>
pointers to data members is given in section
<a href="cplusplus17.html#STABSORT">17.4.60</a>, in the context of the <a name="an2123"></a>
<code>stable_sort()</code> <a name="an2124"></a>
generic algorithm.
<p>
<a name="l219"></a>
<h2>15.4: Pointers to static members</h2>
    <a name="pointermembers/static"></a>Static <a name="an2125"></a>
 members of a class exist without an object of their
class. They exist <em>separately from</em> any object of their class.  When these
static members are public, they can be accessed as global entities, albeit
that their class names are required when they are used.
<p>
Assume that a class <code>String</code> has a public static member function
<code>int n_strings()</code>, returning the number of string objects created so
far. Then, without using any <code>String</code> object the function
<code>String::n_strings()</code> may be called:
        <pre>
    void fun()
    {
        cout &lt;&lt; String::n_strings() &lt;&lt; endl;
    }
</pre>
    Public static members can usually be accessed like global entities (but
see section <a href="cplusplus10.html#CALLINGCONVENTION">10.2.1</a>).  Private static members, on the other
hand, can be accessed only from within the context of their class: they can
only be accessed from inside the member functions of their class.
<p>
Since static members have no associated objects, but are comparable to
global functions and data, their addresses can be stored in ordinary pointer
variables, operating at the <a name="an2126"></a>
global level. Actually, using a
    <a name="an2127"></a>
pointer to member to address a static member of a class would produce a
<a name="an2128"></a>
compilation error.
<p>
For example, the address of a static member function <code>int
String::n_strings()</code> can simply be stored in a variable <code>int (*pfi)()</code>, even
though <code>int (*pfi)()</code> has <em>nothing</em> in common with the <code>class
String</code>. This is illustrated in the next example:
        <pre>
    void fun()
    {
        int (*pfi)() = String::n_strings;
                    // address of the  static member function

        cout &lt;&lt; (*pfi)() &lt;&lt; endl;
                    // print the value produced by String::n_strings()
    }
</pre>
<p>
<a name="l220"></a>
<h2>15.5: Pointer sizes</h2>
    <a name="pointermembers/sizes"></a>    A peculiar characteristic of pointers to members is that their sizes
        <a name="an2129"></a>

        <a name="an2130"></a>

    differ from those of `normal' pointers. Consider the following little
program:
        <pre>
    #include &lt;string&gt;
    #include &lt;iostream&gt;

    class X
    {
        public:
            void fun();
            string d_str;
    };
    inline void X::fun()
    {
        std::cout &lt;&lt; "hello\n";
    }

    using namespace std;

    int main()
    {
        cout
        &lt;&lt; "size of pointer to data-member:     " &lt;&lt; sizeof(&amp;X::d_str) &lt;&lt; "\n"
        &lt;&lt; "size of pointer to member function: " &lt;&lt; sizeof(&amp;X::fun) &lt;&lt; "\n"
        &lt;&lt; "size of pointer to non-member data: " &lt;&lt; sizeof(char *) &lt;&lt; "\n"
        &lt;&lt; "size of pointer to free function:   " &lt;&lt; sizeof(&amp;printf) &lt;&lt; endl;
    }

    /*
        generated output:

        size of pointer to data-member:     4
        size of pointer to member function: 8
        size of pointer to non-member data: 4
        size of pointer to free function:   4
    */
</pre>
    Note that the size of a pointer to a member function is eight bytes,
whereas all other pointers are four bytes (Using the <a name="an2131"></a>
Gnu <a name="an2132"></a>
g++
    <a name="an2133"></a>
compiler).
<p>
In general, these pointer sizes are not explicitly used, but their
differing sizes may cause some confusion in statements like:
        <pre>
    printf("%p", &amp;X::fun);
</pre>
    Of course, <code>printf()</code> is likely not the right tool to produce the
value of these <strong>C++</strong> specific pointers. The values of these pointers can be
inserted into streams when a <code>union</code>, reinterpreting the 8-byte pointers as
a series of size_t <code>char</code> values, is used:
        <pre>
    #include &lt;string&gt;
    #include &lt;iostream&gt;
    #include &lt;iomanip&gt;

    class X
    {
        public:
            void fun();
            std::string d_str;
    };

        inline void X::fun()
        {
            std::cout &lt;&lt; "hello\n";
        }

    using namespace std;

    int main()
    {
        union
        {
            void (X::*f)();
            unsigned char *cp;
        }
            u = { &amp;X::fun };

        cout.fill('0');
        cout &lt;&lt; hex;
        for (unsigned idx = sizeof(void (X::*)()); idx-- &gt; 0; )
            cout &lt;&lt; setw(2) &lt;&lt; static_cast&lt;unsigned&gt;(u.cp[idx]);
        cout &lt;&lt; endl;
    }
</pre>
<p>

<hr>
<ul>
    <li> <a href="cplusplus.html">Table of Contents</a>
    <li> <a href="cplusplus14.html">Previous Chapter</a>
    <li> <a href="cplusplus16.html">Next Chapter</a>
</ul>
<hr>
</body>
</html>
